/*
 * AdpMsg.cpp
 *
 *  Created on: Jan 15, 2013
 *      Author: bird
 */

#include "AdpMsg.h"

namespace Msg {
/**
 * inite the msgid  the key is the process identifier
 */
int AdpMsg::msgid=msgget((key_t)getpid(),0666|IPC_CREAT);
int AdpMsg::MsgSend(const int input_cmd,const long int i_type_is_socket,const long int extend)
{
	assert(i_type_is_socket>=0&&msgid!=-1);
	my_message mymessage;
	mymessage.message_type=i_type_is_socket;
	mymessage.meg_text[0]=input_cmd;
	if(extend!=0)
	{
		memcpy((void*)(mymessage.meg_text+1),(void*)&extend,sizeof(long int));
	}
	if(msgsnd(msgid,(void*)&mymessage,MegLen,IPC_NOWAIT)!=0)
	{
		PrintTrackFun();
		CHandleException::print("send message error\n");
		return -1;
	}
	return 0;
}
int AdpMsg::MsgRcv(const long int i_type_is_socket,char &o_cmdid,long int& o_extend)
{
	assert(i_type_is_socket>=0);
	my_message mymessage;
	int recnum=0;
	if((recnum=msgrcv(msgid,(void*)&mymessage,MegLen,i_type_is_socket,IPC_NOWAIT))==-1)
	{
		//PrintTrackFun();
		//CHandleException::print_socket_excepetion("msgrcv failed \n");
		//printf("%s \n",strerror(errno));
		return -1;
	}
	o_cmdid=mymessage.meg_text[0];
	memcpy((void*)&o_extend,(void*)(mymessage.meg_text+1),sizeof(long int));
	return 0;
}
 int AdpMsg::DeleteMsgQueue()
{
	int reval= msgctl(msgid,IPC_RMID,NULL);
	if(reval==-1)
	{
		PrintTrackFun();
		CHandleException::print("unlink msg queue error\n");
		return -1;
	}
	return 0;
}
} /* namespace Msg */
